package zhibi.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import zhibi.commons.exception.MessageException;
import zhibi.domain.Member;
import zhibi.domain.ScoreLog;
import zhibi.extra.base.BaseController;
import zhibi.extra.pojo.MemberPo;
import zhibi.frame.domain.Page;
import zhibi.frame.mybatis.example.Example;
import zhibi.frame.mybatis.example.ExampleType;
import zhibi.mapper.ScoreLogMapper;
import zhibi.service.MemberService;
import zhibi.utils.DateUtils;
import zhibi.utils.StringUtils;
import zhibi.utils.poi.ExcelUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * Created by 执笔 on 2018/3/24.
 */
@RequestMapping("member")
@Controller
public class MemberController extends BaseController {

    @Autowired
    private MemberService memberService;
    @Autowired
    private ScoreLogMapper scoreLogMapper;

    /**
     * 列表
     *
     * @param member
     * @param page
     * @param model
     * @return
     */
    @RequestMapping("list")
    public String list(MemberPo member, Page page, Model model, String month, Integer endjf, Integer startjf) {
        Example example = Example.getInstance()
                .addParam("m.name", member.getName(), ExampleType.Operation.LIKE)
                .addParam("m.kefu", member.getKefu(), ExampleType.Operation.LIKE)
                .addParam("m.no", member.getNo(), ExampleType.Operation.LIKE)
                .addParam("mobile", member.getMobile(), ExampleType.Operation.LIKE)
                .addParam("m.phone", member.getPhone(), ExampleType.Operation.LIKE)
                .addParam("m.birthday", StringUtils.isEmpty(month) ? month : month + "-", ExampleType.Operation.LIKE)
                .addParam("m.card", member.getCard(), ExampleType.Operation.LIKE)
                .addParam("u.name", member.getUsername(), ExampleType.Operation.LIKE)
                .addParam("m.score", startjf, ExampleType.Operation.LTE)
                .addParam("m.score", endjf, ExampleType.Operation.GTE)
                .addOrder("addtime", ExampleType.OrderType.DESC);

        if (!sessionUser().getType().equals("admin")) {
            example.addParam("m.userid", sessionUser().getId());
        }

        PageInfo<MemberPo> pageInfo = memberService.selectPoByExample(example, page);
        setModelAttribute(model, pageInfo);
        return "member/list";
    }

    /**
     * 导出数据
     *
     * @return
     */
    @RequestMapping(value = "list", params = "export")
    public void export(MemberPo member, HttpServletResponse response, String month, Integer endjf, Integer startjf) throws IOException {
        Example example = Example.getInstance()
                .addParam("m.name", member.getName(), ExampleType.Operation.LIKE)
                .addParam("m.kefu", member.getKefu(), ExampleType.Operation.LIKE)
                .addParam("m.no", member.getNo(), ExampleType.Operation.LIKE)
                .addParam("mobile", member.getMobile(), ExampleType.Operation.LIKE)
                .addParam("m.phone", member.getPhone(), ExampleType.Operation.LIKE)
                .addParam("m.birthday", StringUtils.isEmpty(month) ? month : month + "-", ExampleType.Operation.LIKE)
                .addParam("m.card", member.getCard(), ExampleType.Operation.LIKE)
                .addParam("u.name", member.getUsername(), ExampleType.Operation.LIKE)
                .addParam("m.score", startjf, ExampleType.Operation.LTE)
                .addParam("m.score", endjf, ExampleType.Operation.GTE)
                .addOrder("addtime", ExampleType.OrderType.DESC);

        if (!sessionUser().getType().equals("admin")) {
            example.addParam("m.userid", sessionUser().getId());
        }
        List<MemberPo> list = memberService.selectPoByExample(example, new Page(1, Integer.MAX_VALUE)).getList();
        ServletOutputStream outputStream = response.getOutputStream();
        response.addHeader("Content-Disposition", "attachment;filename=" + DateUtils.formatDate(new Date(), "yyyy-MM-dd-HH-mm-ss") + ".xls");
        ExcelUtils.writeExcel(outputStream, list);
    }

    @GetMapping("add")
    public String add() {
        return "member/add";
    }

    @PostMapping("add")
    public String add(Member member) {
        Member temp = new Member();
        temp.setNo(member.getNo());
        int size = memberService.select(temp).size();
        if (size > 0) throw new MessageException("该会员编号已经存在");
        temp = new Member();
        temp.setCard(member.getCard());
        size = memberService.select(temp).size();
        if (size > 0) throw new MessageException("该身份证号码已经存在");
        member.setAddtime(new Date());
        member.setUserid(sessionUser().getId());
        member.setScore(0D);
        //
        member.setBirthday(member.getCard().substring(10, 12) + "-" + member.getCard().substring(12, 14));
        memberService.insertSelective(member);
        return redirect("list");
    }

    @GetMapping("detail/{id}")
    public String detail(@PathVariable Integer id, Model model) {
        Member member = memberService.selectByPrimaryKey(id);
        if (null == member) throw new MessageException("该会员不存在");
        model.addAttribute(member);
        return "member/detail";
    }

    @PostMapping("update")
    public String update(Member member) {

        Example example = Example.getInstance().addParam("card", member.getCard())
                .addParam("id", member.getId(), ExampleType.Operation.NOTEQ);
        int size = memberService.selectCountByExample(example);
        if (size > 0) throw new MessageException("该身份证号码已经存在");

        example = Example.getInstance().addParam("no", member.getNo())
                .addParam("id", member.getId(), ExampleType.Operation.NOTEQ);
        size = memberService.selectCountByExample(example);
        if (size > 0) throw new MessageException("该会员编号已经存在");

        member.setBirthday(member.getCard().substring(10, 12) + "-" + member.getCard().substring(12, 14));
        memberService.updateByPrimaryKeySelective(member);
        return redirect("list");
    }

    @RequestMapping("scoreLog/{id}")
    public String scoreLog(@PathVariable Integer id, Page page, Model model) {
        Example example = Example.getInstance().addParam("memberid").addOrder("addtime", ExampleType.OrderType.DESC);
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<ScoreLog> scoreLogs = scoreLogMapper.selectByExample(example);
        PageInfo<ScoreLog> pageInfo = new PageInfo<>(scoreLogs, 5);
        setModelAttribute(model, pageInfo);
        return "scorelog/list";
    }


}
